package com.example.mynewsapp.fragment.news

import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mynewsapp.R
import com.example.mynewsapp.activity.DetailNews
import com.example.mynewsapp.adapter.NewsAdapter
import com.example.mynewsapp.fragment.Fragment.country
import com.example.mynewsapp.fragment.Fragment.db
import com.example.mynewsapp.fragment.Fragment.news_adapter
import com.example.mynewsapp.model.ArticaleModel
import com.example.mynewsapp.model.NewsItem
import com.example.mynewsapp.model.NewsModel
import com.example.mynewsapp.network.ApiInterface
import com.example.mynewsapp.network.Constants
import com.example.mynewsapp.network.Constants.API_KEY
import com.example.mynewsapp.network.HttpRequest
import com.example.mynewsapp.util.Utils
import kotlinx.android.synthetic.main.news_view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

abstract class FragmentNewsBase : Fragment() {

    abstract fun getCategory () : String?

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.news_view, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        generateDummyList()

        down_pull_update.setColorSchemeResources(R.color.colorPrimaryDark)
        down_pull_update.setOnRefreshListener {
            var handler = Handler()
            handler.postDelayed({
                generateDummyList()
                down_pull_update.isRefreshing = false
                refreshSuccess()
            }, 1000)
        }
    }

    private fun init() {
        val list = ArrayList<NewsItem>()

        for (i in 0..10) {
            val drawable = null
            val update = getString(R.string.loading)
            val ctry = getString(R.string.loading)
            val desc = getString(R.string.loading)
            val date = getString(R.string.loading)
            val url = ""
            var like = "no"

            val item = NewsItem(drawable, update, ctry, desc, date, url, like)
            list += item
        }
        onSetList(list)
    }

    private fun getCall () : Call<NewsModel> {
        country = Utils.getCountry()
        val apiInterface = HttpRequest.createApi(Constants.BASE_NEWS_URL).create(ApiInterface::class.java)

        when (getCategory()) {
            "business" -> return apiInterface.getBusiness(country, getCategory(), API_KEY)
            "entertainment" -> return apiInterface.getEntertainment(country, getCategory(), API_KEY)
            "health" -> return apiInterface.getHealth(country, getCategory(), API_KEY)
            "sports" -> return apiInterface.getSports(country, getCategory(), API_KEY)
            "technology" -> return apiInterface.getTechnology(country, getCategory(), API_KEY)
        }
        return apiInterface.getHeadlines(country, API_KEY)
    }

    private fun generateDummyList(){

        val list = ArrayList<NewsItem>()

        getCall().enqueue(object : Callback<NewsModel> {
            override fun onResponse(call: Call<NewsModel>, response: Response<NewsModel>) {
                if (response.isSuccessful && response.body() != null) {
                    com.example.mynewsapp.fragment.Fragment.modelArticle = response.body()?.data as MutableList<ArticaleModel>
                    for (i in 0 until com.example.mynewsapp.fragment.Fragment.modelArticle.size) {

                        val drawable = com.example.mynewsapp.fragment.Fragment.modelArticle[i].urlToImage
                        val update = Utils.DateTimeHourAgo(com.example.mynewsapp.fragment.Fragment.modelArticle[i].publishedAt)
                        val country = com.example.mynewsapp.fragment.Fragment.modelArticle[i].source.name + if (com.example.mynewsapp.fragment.Fragment.modelArticle[i].author==null) "" else "-"+ com.example.mynewsapp.fragment.Fragment.modelArticle[i].author
                        val desc = com.example.mynewsapp.fragment.Fragment.modelArticle[i].title
                        val date = Utils.DateFormat(com.example.mynewsapp.fragment.Fragment.modelArticle[i].publishedAt)
                        val url = com.example.mynewsapp.fragment.Fragment.modelArticle[i].url

                        var like = "no"
                        val cursor =db!!.query("favorite", null, null, null, null, null, null)
                        while (cursor.moveToNext()) {
                            val url_db = cursor.getString(cursor.getColumnIndex("newsUrl"))
                            if (url_db == url) {
                                like = "yes"
                                break
                            }
                        }
                        cursor.close()

                        val item = NewsItem(drawable, update, country, desc, date, url, like)
                        list += item
                    }

                    onSetList(list)

                }
            }

            override fun onFailure(call: Call<NewsModel>, t: Throwable) {
                sign()
            }

        })

    }

    // 设置列表
    private fun onSetList(list: ArrayList<NewsItem>) {

        if (recycler_view==null)return

        recycler_view.layoutManager = LinearLayoutManager(context)
        news_adapter = NewsAdapter(list!!,context!!)
        recycler_view.adapter = news_adapter


        news_adapter?.mOnRecyclerViewItemClick = object :
                NewsAdapter.OnRecyclerViewItemClick {
            override fun OnItemClick(view: View?, content: NewsItem, position: Int) {

                ifNewsExist(content)
                addData(content)

                val intent = Intent(context, DetailNews::class.java)
                intent.putExtra(DetailNews.DETAIL_NEWS, content)
                startActivity(intent)
            }

            override fun OnLongClick(view: View?, t: NewsItem, position: Int) {
            }
        }
    }

    private fun addData (content: NewsItem) {
        if (content.url == "") return
        //创建存放数据的ContentValues对象
        val values = ContentValues()
        values.put("newsImage", content.image)
        values.put("newsUpdate", content.update)
        values.put("newsCountry", content.country)
        values.put("newsTitle", content.title)
        values.put("newsDate", content.date)
        values.put("newsUrl", content.url)
        values.put("newsLike", content.like)
        //数据库执行插入命令
        db!!.insert("history", null, values)

    }

    private fun ifNewsExist (content: NewsItem){

        if (content.url == "") return

        val cursor = db!!.query("history", null, null, null, null, null, null)
        while (cursor.moveToNext()) {
            val url = cursor.getString(cursor.getColumnIndex("newsUrl"))
            if (url == content.url) {
                db!!.delete("history","newsUrl=?", arrayOf(url))
                break
            }
        }
        cursor.close() // 关闭游标，释放资源
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        com.example.mynewsapp.fragment.Fragment.mActivity = context as Activity
    }

    private fun sign() {
        if (this.isAdded){
            Toast.makeText(com.example.mynewsapp.fragment.Fragment.mActivity, getString(R.string.loadFail), Toast.LENGTH_SHORT).show()
        }
    }

    private fun refreshSuccess () {
        if (this.isAdded){
            Toast.makeText(com.example.mynewsapp.fragment.Fragment.mActivity, getString(R.string.refreshSuccess), Toast.LENGTH_SHORT).show()
        }
    }
}